package thread.sync;

import static java.lang.System.out;

/**
 * This is an ATM example. Two threads are trying to get an amount of 300 from an account 4321. <br>
 * The initial balance is 531. <br>
 * Comment out synchronized keyword from following line<br>
 * public synchronized boolean withdrawal ( int amount ) { <br>
 */

public class ATM extends Thread {
	final static int ACCOUNT_NO = 4321;
	static int balance = 531;
	
	int atmNo;

	ATM(int no) {
		this.atmNo = no;
	}

	public void run() {
		withdraw(300, atmNo);
	}
	public static void main(String[] args) {
		
    	ATM atm1 = new ATM (1);    
    	ATM atm2 = new ATM (2);
    	atm1.start();     
    	atm2.start();
	}
	public static synchronized void withdraw (int amount, int atmNo) {
    	
    	out.println("ATM No : " + atmNo + " , Balance: " + balance+"\n" );
    	out.println("Withdrawal Amount :" + amount );
    	
    	if ( amount <= balance ) {  
    		balance -= amount; 
    		out.println("New balance : " + balance +"\n" );  
    		
    	}
    	else {
      		out.println("Insufficient funds. \n");
		}
  	}
}

//Output with synchronized
/*ATM No : 1 , Balance: 531

Withdrawal Amount :300
New balance : 231

ATM No : 2 , Balance: 231

Withdrawal Amount :300
Insufficient funds.
*/ 

//Output without synchronized
//Not sure which thread get the amount

/*ATM No : 1 , Balance: 531

Withdrawal Amount :300
New balance : 231

ATM No : 2 , Balance: 531

Withdrawal Amount :300
Insufficient funds. */

